<?php

namespace App\Http\Controllers\UserApi;

use App\Http\Controllers\Controller;
use App\Jobs\CourseReminder;
use App\Services\Admin\Reservation;
use App\Services\Api\UserIntegralServices;
use Illuminate\Http\Request;

use App\Http\Requests\UserApi\SubscribeRequest;
use App\Models\UserSubscribe;
use App\Services\Api\SubscribeServices;
use App\Models\ClassBase;
use App\Models\Classroom;
use App\Models\ClassBaseInfo;
use App\Models\GroupClass;
use App\Models\ClassQuarterly;
use App\Services\Api\UserRankExpServices;
use Illuminate\Support\Facades\DB;
use App\Models\UserCoupon;
use App\Services\Api\CouponServices;
use App\Jobs\CloseOrder;


class UserSubscribeController extends BaseController
{

    public function create_subscribe(SubscribeRequest $subscribeRequest,
                                     UserSubscribe $subscribeModel,
        //SubscribeServices $subscribeServices,
        // UserRankExpServices $expServices,
        // ClassBase $classBase,
                                     ClassBaseInfo $baseInfo,
                                     ClassQuarterly $classQuarterly,
                                     UserIntegralServices $integralServices,
                                     CouponServices $couponServices)
    {

        date_default_timezone_set('PRC');
        //开启事务
        DB::beginTransaction();
        try {

            //路由过滤
            $create_subscribe_rule = $couponServices->create_subscribe_rule();

            $classBase = $create_subscribe_rule['classBase'];

            $start_time = $create_subscribe_rule['start_time'];

            $end_time = $create_subscribe_rule['end_time'];

            $teacher = $create_subscribe_rule['teacher'];

            $input = $subscribeRequest->post();

            $classroom_number = $subscribeModel->ClassUseNumber($classBase->classsroom->id, date("Y-m-d H:i:s", $start_time), date("Y-m-d H:i:s", $end_time));

            //排满人排队
            if ($classroom_number >= $classBase->class_number_people) {
                $full_queue = $couponServices->full_queue($start_time, $end_time);
                $input['subscribe_status'] = 1;
                $input['queue_number'] = $full_queue['queue_number'];
            } else {
                $input['subscribe_status'] = 2;
            }

            //使用記錄id
            $user_vip_use_record_id = 0;

            //vip使用
            if(!empty($input['vip_id'])){
                $user_vip_use_record_id = $couponServices->vip($input, $classBase->class_base->class_name);
                $input['buy_type'] = 4;
            }

            //补课操作
            if (!empty($input['original_subscribe_id'])) {
                $couponServices->make_up($classBase);
                $input['buy_type'] = 3;
            }

            //捆綁卷使用
            if (!empty($input['discount_order_id'])) {
                $couponServices->discount_meal();
                $input['is_discount'] = 1;
            }

            $money = 0;

            //现金卷使用
            if (!empty($input['user_coupon_id'])) {
                $money = $couponServices->original_subscribe($classBase, $start_time);
                $input['is_coupon'] = 1;
            }

            //普通積分預約  或 //因为用了vip就不需要扣积分了
            if (empty($input['original_subscribe_id']) && empty($input['user_coupon_id']) && empty($input['discount_order_id']) && empty($input['vip_id'])) {
                $money = $classBase->class_base->class_price;
            }

            if ($money > 0) {

                if ($input['subscribe_status'] == 1) {
                    $use_integral_msg_title = '候補課程';
                } else if ($input['subscribe_status'] == 2) {
                    $use_integral_msg_title = '購買課程';
                }

                $start_time_msg = date("H:i", $start_time);
                $end_time_msg = date("H:i", $end_time);

                $end_time_string = "{$start_time_msg}-{$end_time_msg}";

                $use_integral_msg = [
                    $use_integral_msg_title,
                    "-{$money}分",
                    date("Y-m-d", $start_time),
                    $end_time_string,
                    $classBase->class_base->class_name
                ];

                //扣减积分
                $msg = implode("/", $use_integral_msg);

                $refund = $integralServices->use_integral(auth('api')->user()->id, $money, $msg);

                if (empty($refund)) throw new \Exception('扣款失败');

            }

            $input['user_id'] = auth('api')->user()->id;
            $input['class_base_id'] = $classBase->class_base_id;
            $input['store_id'] = $classBase->store_id;
            $input['class_name'] = $classBase->class_base->class_name;
            $input['store_name'] = $classBase->store->store_name;
            $input['class_classroom_id'] = $classBase->classsroom->id;
            $input['class_classroom_name'] = $classBase->classsroom->numbering;
            $input['teacher_id'] = $teacher['id'];
            $input['user_vip_use_record_id'] = $user_vip_use_record_id;
            $input['teacher_name'] = $teacher['teacher_name'];
            $input['use_integral'] = $money;
            $input['is_tutoring'] = $input['is_tutoring'] ?? 2;
            $input['class_time'] = date("Y-m-d H:i:s", $start_time);
            $input['end_time'] = date("Y-m-d H:i:s", $end_time);
            $input['created_at'] = date("Y-m-d H:i:s");

            //快照數據
            $input['class_info'] = json_encode($classBase);
            //$input['refund_data'] = json_encode($refund);

            $id = $subscribeModel->create($input)->id;

            if($input['subscribe_status'] == 1){
                //計算時間  候补消息
                $close_time = $start_time - time();
                $this->dispatch(new CloseOrder($subscribeModel, $close_time, $id));
            }

            //目的是因为微信消息模板只能发一次 所以订阅了发送成功消息，就不能发送最低人数判断消息了
            $bool = 1;

            if($input['subscribe_status'] == 2 && !empty($create_subscribe_rule['start_before_minutes_value']) && !empty($create_subscribe_rule['minimum_number'])){
                //距离系统判断人数是否够延后10秒添加队列
                $delay = ($create_subscribe_rule['start_time_minutes'] - time()) + 10;
                $this->dispatch(new CourseReminder($subscribeModel,$delay, $id));
                $bool = 0;
            }

            if($input['subscribe_status'] == 2 && $bool){
                //预约成功消息
                $this->dispatch(new CourseReminder($subscribeModel,5, $id));
            }

            DB::commit();

            if ($id) {
                return $this->success();
            } else {
                throw new \Exception('保存失敗');
            }

        } catch (\Exception $e) {
            //接收异常处理并回滚
            DB::rollBack();
            return $this->fail($e->getMessage());
        }

    }

    public function my_subscribe(Request $request, UserSubscribe $subscribeModel, SubscribeServices $subscribeServices)
    {
        //$where = $request->input('order');
        $data = $subscribeServices->my_subscribe($request, auth('api')->user()->id, $subscribeModel);
        return $this->success($data);
    }

    public function change_subscribe(Request $request, UserSubscribe $subscribeModel, SubscribeServices $subscribeServices)
    {
        DB::beginTransaction();

        try {
            $check_change = $subscribeServices->check_change_subscribe($request->subscribe_id);

            if (!$check_change) throw new \Exception('超时不能取消');

            //同一課程15天內不能取消2次
            $subscribeObj = $subscribeModel->select([
                'id',
                'class_base_info_id',
                'class_time',
                'end_time',
            ])->WhereID($request->subscribe_id)
                ->first();
            $change_number = UserSubscribe::where('class_base_info_id', $subscribeObj->class_base_info_id)
                //->where('class_time',$subscribeObj->class_time)
                //->where('end_time',$subscribeObj->end_time)
                ->whereDate('created_at', '<=', date("Y-m-d", strtotime("-15 day")))
                ->where('user_id', $subscribeObj->user_id)
                ->where('subscribe_status', 4)
                ->count();

            if ($change_number >= 2) {
                throw new \Exception('15天內不能取消同一課程2次');
            }

            $subscribeServices->change_subscribe($request, $subscribeModel);

            DB::commit();

        }catch (\Exception $e){

            return $this->fail($e->getMessage());

        }

        return $this->success();

    }


}
